package com.demomaster.quickserialport;

import java.util.HashMap;
import java.util.Map;

public class QuickSerialPort {

    private Map<String, SerialPortClient> serialPortClientMap;
    private static QuickSerialPort instance;

    public static QuickSerialPort getInstance() {
        if(instance==null){
            instance = new QuickSerialPort();
        }
        return instance;
    }

    private QuickSerialPort(){
        serialPortClientMap = new HashMap<>();
    }

    public SerialPortClient openSerialPort(String path, int baudrate) throws Exception {
        String key = path+"_"+baudrate;
        if(!serialPortClientMap.containsKey(key)){
            SerialPortClient serialPortClient = new SerialPortClient();
            serialPortClient.openSerialPort(path,baudrate);
            serialPortClientMap.put(key,serialPortClient);
            return serialPortClient;
        }else {
             return serialPortClientMap.get(key);
        }
    }
    public void closeSerialPort(String path, int baudrate) {
        String key = path+"_"+baudrate;
        if(serialPortClientMap.containsKey(key)){
            serialPortClientMap.get(key).closeSerialPort();
            serialPortClientMap.remove(key);
        }
    }
}
